package de.rosstauscher.comparandum.util;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;

import de.rosstauscher.comparandum.render.IRenderable;

/*****************************************************************************
 * Some helper methods for rendering objects to images. 
 * @author Bernd Rosstauscher (java@rosstauscher.de) Copyright 2011
 ****************************************************************************/

public class RenderUtil {
	
	private static final String DEFAULT_IMAGE_FORMAT = "png";
	
	public static final int DEFAULT_IMAGE_TYPE = BufferedImage.TYPE_INT_ARGB;
	
	/*************************************************************************
	 * Renders the given renderable object as Image.
	 * @param r the renderable object 
	 * @return an Image representing this object.
	 ************************************************************************/
	
	public static BufferedImage renderToImage(IRenderable r) {
		Dimension d = r.getDimension();
		BufferedImage bi = new BufferedImage(d.width, d.height, DEFAULT_IMAGE_TYPE);
		Graphics2D g = bi.createGraphics();
		r.paint(g);
		g.dispose();
		return bi;
	}
	
	/*************************************************************************
	 * Renders the given renderable object and saves it to an image file.
	 * @param r the renderable object 
	 * @param destination file to write the image to.
	 * @throws IOException on error.
	 ************************************************************************/
	
	public static void renderToDisk(IRenderable r, File destination) throws IOException {
		BufferedImage img = RenderUtil.renderToImage(r);
		String extension = getExtensionFromFile(destination, DEFAULT_IMAGE_FORMAT);
		Iterator<ImageWriter> writers = ImageIO.getImageWritersBySuffix(extension);
		ImageWriter writer = writers.next();
		writer.setOutput(new FileImageOutputStream(destination));
		writer.write(img);
		writer.dispose();
	}

	/*************************************************************************
	 * Gets a file extension from a file name without a trailing dot.
	 * @param destination file to extrac the extension from.
	 * @param defaultExt the default to use if the file has no extension.
	 * @return the file extension or the default extenstion if the given file has none.
	 ************************************************************************/
	
	private static String getExtensionFromFile(File destination, String defaultExt) {
		String extension = "";
		String fileName = destination.getName();
		int index = fileName.lastIndexOf('.');
		if (index >= 0)  {
			extension = fileName.substring(index+1);
		}
		return extension.length() > 0 ? extension : defaultExt;
	}


}

